// CONFIGURAÇÕES INICIAIS:
$(function () {
  $('[data-toggle="popover"]').popover();
  $('[data-toggle="tooltip"]').tooltip();
  $('.selectpicker').selectpicker('render');
  
  var nav = $('.navbar');
  var con = $('#conteudo');

  $(window).scroll(function () {
      //console.log($(this).scrollTop());
      if ($(this).scrollTop() > 100) {
          nav.addClass("f-nav");
          con.addClass("adjust");
      } else {
          nav.removeClass("f-nav");
          con.removeClass("adjust");
      }
  });
  
  //console.log(document.documentElement.scrollHeight);
  //console.log(document.documentElement.clientHeight);
  
  if(document.documentElement.scrollHeight <= document.documentElement.clientHeight){
	  $('#footer').addClass('footer-fixed');
  }
  
});



//Plugins framework ///////////////////////////////////////////////////////////
$.fn.serializeObject = function(){
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
$.fn.wordComplete = function(params){
	if(params.minLength == undefined)
		params.minLength = 1;	
	if(params.delay == undefined)
		params.delay = 300;
	if(params.titleIconInfo == undefined)
		params.titleIconInfo = "Selecione uma entidade...";	
	if(params.titleIconOk == undefined)
		params.titleIconOk = "Entidade selecionada!";
	var compId = $(this).attr('id');
	if(compId == undefined)
		return;
	
	var entitylabel = $(this).attr('entitylabel');
	var entityid = $(this).attr('entityid');
	var selected = false;
	var myComp = $(this);
	var boolean = false;
	/*var img = $("<img src='assets/autocomplete_info.png' title='" + params.titleIconInfo + "' />");*/
	var inputCod = $('<input type="hidden" id="' + $(this).attr('id') + '_id" name="' + $(this).attr('id') + '_id" value="0"/>');	
	if(entityid != '' && entityid != undefined && entitylabel != '' && entitylabel != undefined){
		inputCod = $('<input type="hidden" id="' + $(this).attr('id') + '_id" name="' + $(this).attr('id') + '_id" value="' + entityid + '"/>');	
		$(this).val(entitylabel);
		boolean = true;
	}
	/*$(this).parent().append(img);*/
	$(this).parent().append(inputCod);
	/*$(this).autocomplete({
		source: params.source,
		minLength: params.minLength,
		delay: params.delay,
		search: function(event, ui) {
			img = '<img class="imginfo_" src="assets/autocomplete_loading.gif" title="Pesquisando"/>';
			if($($($("#nm_unidade_trabalho")[0].nextElementSibling)[0].nextElementSibling).find("span").find("img").length == 0){
				$($($(this)[0].nextElementSibling)[0].nextElementSibling).find("span").removeClass("fa-search fa-exclamation-triangle fa-check");
				$($($(this)[0].nextElementSibling)[0].nextElementSibling).find("span").append(img);
			}
		},
		response: function( event, ui ) {
			$($($(this)[0].nextElementSibling)[0].nextElementSibling).find("span").find("img").remove();
			$($($(this)[0].nextElementSibling)[0].nextElementSibling).find("span").removeClass("fa-search fa-check").addClass("fa-exclamation-triangle").css("color","#f48211");
			$($($(this)[0].nextElementSibling)[0].nextElementSibling).find("span").attr("title",params.titleIconInfo);
		},
		select: function( event, ui ) {
			selected = true;
			$(inputCod).val(ui.item.id);
			//$(img).attr("src", "assets/autocomplete_ok.png");
			//$(img).attr("title", params.titleIconOk);
			$($($(this)[0].nextElementSibling)[0].nextElementSibling).find("span").removeClass("glyphicon-search glyphicon-warning-sign").addClass("glyphicon-ok").css("color","green");
			$($($(this)[0].nextElementSibling)[0].nextElementSibling).find("span").attr("title", params.titleIconOk);
		}
	}).data("ui-autocomplete")._renderItem = function(ul, item){
		var matcher = new RegExp("("+$.ui.autocomplete.escapeRegex($(myComp).val())+")", "ig" );
		return $("<li>").append("<a>" + item.label.replace(matcher, "<strong>$1</strong>") + "</a>").appendTo(ul);
	};*/
	$(this).keyup(function(event){
		if(!event.shiftKey && event.keyCode != 16){ //shift-tab
			if(event.keyCode != 13 && event.keyCode != 35 && event.keyCode != 36 
				&& event.keyCode != 37 && event.keyCode != 38 && event.keyCode != 39 && event.keyCode != 40){ //enter, home/end e teclas direcionais
				if(!selected && $(this).val().length >= params.minLength){
					$(inputCod).val(0);
					$($($(this)[0].nextElementSibling)[0].nextElementSibling).find("span").removeClass("glyphicon-search glyphicon-ok").addClass("glyphicon-warning-sign").css("color","#f48211");
					$($($(this)[0].nextElementSibling)[0].nextElementSibling).find("span").attr("title",params.titleIconInfo);
				}
			}
		}
		selected = false;		
	});
	if(boolean){
		$($($(this)[0].nextElementSibling)[0].nextElementSibling).find("span").removeClass("glyphicon-search glyphicon-warning-sign").addClass("glyphicon-ok").css("color","green");
		$($($(this)[0].nextElementSibling)[0].nextElementSibling).find("span").attr("title", params.titleIconOk);
	}
	$(this).attr("placeholder","DIGITE INEP OU NOME DA UNIDADE DE TRABALHO");
};


$.fn.dialogFind = function(params){
    var dialogId = $(this).attr('id');	
	$(this).dialog({
		autoOpen: false,
		width: 720,
		height: 450,
		modal: true		
	});	
	dialogs[dialogId] = {type:'find', partial:params.partial, testFunction:params.testFunction};
	dialogRefresh(dialogId);	
};
///////////////////////////////////////////////////////////////////////////////
//Manipula��o de dialogs, pagina��o e relat�rios //////////////////////////////
var dialogs = {};
function dialogRefresh(id){
	if(dialogs[id] != undefined){
		switch(dialogs[id].type){
			case 'find':
				$('#' + id + '_loader').dialog('close');
				$('#' + id + '_form').submit(function(){
					if(dialogs[id].testFunction()){
						$('#' + id + '_loader').dialog('open');
						$('#' + id).load('partials/' + dialogs[id].partial + '.php', $('#' + id + '_form').serializeObject(), function(){
							dialogRefresh(id);	
						});
					}
					return false;
				});	
				$('#' + id + '_submit').button({icons:{primary:'ui-icon-search'}});
				$('.buttonPag').hover(
					function(){ $(this).addClass('ui-state-hover'); }, 
					function(){ $(this).removeClass('ui-state-hover'); }
				);
				$('.tablelist tr').each(function(){
					$(this).hover(
						function(){ $(this).addClass('hover'); }, 
						function(){ $(this).removeClass('hover'); }
					);
				});
				$('.datepicker').each(function(index){
					$(this).datepicker();
				});
				$('#' + id).append('<div id="' + id + '_loader" title="Carregando..."><div align="center"><img src="assets/loading.gif"/></div></div>');
				$('#' + id + '_loader').dialog({
					autoOpen: false,
					width: 120,
					height: 100,
					modal: true,
					closeOnEscape: false,
					dialogClass: 'no-close',
					hide: {effect: "fade"}
				});
			break;
		}
	}
}
function setPaginacaoAjaxSimple(dialogId, partial, page){
	$('#' + dialogId).load('partials/' + partial + '.php' + '?' + page, $('#' + dialogId + '_form').serializeObject());	
}
function setPaginacaoAjax(dialogId, partial, page){
	$('#' + dialogId).load('partials/' + partial + '.php' + '?' + page, $('#' + dialogId + '_form').serializeObject(), function(){
		dialogRefresh(dialogId);
	});	
}
function setPaginacao(link){
	$('#formPaginacao').attr('action', link);
	$('#formPaginacao').submit();
}
function setReport(key, value){
	$form = $('<form method="post"></form>');
	$form.append('<input type="hidden" name="' + key + '" value="' + value + '"/>');
	$('body').append($form);
	$form.submit();	
}
///////////////////////////////////////////////////////////////////////////////
//M�scaras, formata��o e valida��o ////////////////////////////////////////////
function mask(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmask()",1)
}
function execmask(){
    v_obj.value=v_fun(v_obj.value)
}
function money(v){
	v=v.replace(/\D/g,"")
	v=v.replace(/[0-9]{14}/,"inv�lido")
    v=v.replace(/(\d{1})(\d{11})$/,"$1.$2")
    v=v.replace(/(\d{1})(\d{8})$/,"$1.$2")
	v=v.replace(/(\d{1})(\d{5})$/,"$1.$2")
	v=v.replace(/(\d{1})(\d{1,2})$/,"$1,$2")
	return v;
}
function format(o,m){
	i = o.value.length;
	saida = m.substring(0,1);	
	texto = m.substring(i);	
	if(texto.substring(0,1) != saida)
		o.value += texto.substring(0,1);	
}
function numeros(v){
    return v.replace(/\D/g,"")
}
function data(v){
   	v=v.replace(/\D/g,"")                          
    v=v.replace(/^(\d{2})(\d)/,"$1/$2")                       
    v=v.replace(/(\d{2})(\d)/,"$1/$2")             
    return v
}
function valor(v){  
    v=v.replace(/\D/g,"") 
    v=v.replace(/[0-9]{12}/,"inv���lido") 
    v=v.replace(/(\d{1})(\d{8})$/,"$1.$2")
    v=v.replace(/(\d{1})(\d{5})$/,"$1.$2")
    v=v.replace(/(\d{1})(\d{1,2})$/,"$1,$2")
    return v;
}
function cpf(v){
	v=v.replace(/\D/g,"")                          
    v=v.replace(/^(\d{3})(\d)/,"$1.$2")             
    v=v.replace(/^(\d{3})\.(\d{3})(\d)/,"$1.$2.$3")      
    v=v.replace(/(\d{3})(\d)/,"$1-$2")             
    return v
}
function cnpj(v){
	v=v.replace(/\D/g,"")
	v=v.replace(/^(\d{12})(\d)/,"$1-$2")
	v=v.replace(/^(\d{8})(\d)/,"$1/$2")
	v=v.replace(/^(\d{5})(\d)/,"$1.$2")
	v=v.replace(/^(\d{2})(\d)/,"$1.$2")
	return v
}
function cep(v){
    v=v.replace(/\D/g,"")                          
    v=v.replace(/^(\d{2})(\d)/,"$1.$2")                       
    v=v.replace(/(\d{3})(\d)/,"$1-$2")             
    return v
}
function telefone(v){        
	v=v.replace(/\D/g,"")   
    v=v.replace(/^(\d)/,"($1")
    v=v.replace(/^\((\d\d)(\d)/g,"($1) $2") 
    v=v.replace(/(\d{4})(\d)/,"$1-$2")  
    return v
}
function checkCpf(cpf){   
	cpf = remove(cpf, ".");
	cpf = remove(cpf, "-");      
	if(cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" ||
		  cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" ||
		  cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" ||
		  cpf == "88888888888" || cpf == "99999999999"){
		  return false;   
	}
	soma = 0;
	for(i = 0; i < 9; i++)
		 soma += parseInt(cpf.charAt(i)) * (10 - i);
	resto = 11 - (soma % 11);
	if(resto == 10 || resto == 11)
		 resto = 0;
	if(resto != parseInt(cpf.charAt(9))){
		 return false;
	}
	soma = 0;
	for(i = 0; i < 10; i ++)
		 soma += parseInt(cpf.charAt(i)) * (11 - i);
	resto = 11 - (soma % 11);
	if(resto == 10 || resto == 11)
		 resto = 0;
	if(resto != parseInt(cpf.charAt(10))){
	 return false;
	}
	return true;
}
function checkCnpj(cnpj){
    var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
    digitos_iguais = 1;
        
	if (cnpj.length < 14 && cnpj.length < 15) {
		return false;				
	}
	for (i = 0; i < cnpj.length - 1; i++)
		if (cnpj.charAt(i) != cnpj.charAt(i + 1)){
				digitos_iguais = 0;
			break;
						
				}
	if (!digitos_iguais){
		tamanho = cnpj.length - 2
		numeros = cnpj.substring(0,tamanho);
		digitos = cnpj.substring(tamanho);
		soma = 0;
		pos = tamanho - 7;
		for (i = tamanho; i >= 1; i--){
				soma += numeros.charAt(tamanho - i) * pos--;
			if (pos < 2)
				pos = 9;
		}
		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
		if (resultado != digitos.charAt(0))
				return false;
		tamanho = tamanho + 1;
		numeros = cnpj.substring(0,tamanho);
		soma = 0;
		pos = tamanho - 7;
		for (i = tamanho; i >= 1; i--){
				soma += numeros.charAt(tamanho - i) * pos--;
			if (pos < 2)
				pos = 9;
		}
		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
		if (resultado != digitos.charAt(1))
				return false;
		return true;
		}
	else
		return false;
}
function checkData(data) {
	data = remove(data, "/");
	if(data.length != 8)
		return false;
        
    var dia=0, mes=0, ano=0;
    dia = parseInt(data.substr(0,2), 10);
    mes = parseInt(data.substr(2,2), 10);
    ano = parseInt(data.substr(4,4), 10);
    
	if (data =="")
		return false;
    if ((mes < 1) || (mes > 12)) {
		return false;           
    }   
    if ((dia < 1) || (dia > 31)){
		return false;
    }        
	if ((ano < 1500) || (ano > 2100) ){
		return false;
	}   
	if ((mes == 2) || (mes == 4) || (mes == 6) || (mes == 9) || (mes == 11)) {
		if (dia > 30) {
			return false;
		}
        if (mes == 2) {
            if (ano % 4 == 0) {
                if (dia > 29) {
                    return false;
                }
            }
            else {
                if (dia > 28) {
                    return false;
                }
            }
        }
    }   
	return true;    
} 
function checkMail(mail){
	var er = /^[a-zA-Z0-9][a-zA-Z0-9\._-]+@([a-zA-Z0-9\._-]+\.)[a-zA-Z-0-9]{2}/;
	if(typeof(mail) == "string"){
		if(er.exec(mail)){
			return true; 
		}
	}
}
function remove(str, sub){
	i = str.indexOf(sub);
	r = "";
	if (i == -1) return str;
	r += str.substring(0,i) + remove(str.substring(i + sub.length), sub);
	return r;   
}
function addslashes(str) {
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\0/g,'\\0');
	return str;
}
function stripslashes(str) {
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\0/g,'\0');
	str=str.replace(/\\\\/g,'\\');
	return str;
}
function updateTips(obj, t, timer){
	if(timer == undefined) timer = 3500;
	groww(t, '', 'warning', 'warning', timer);
	obj.focus().parent().addClass("has-error");
	$(document).find("html, body").animate({ scrollTop: 0 }, "slow");
}

function updateTipsModal(obj, t, title,timer){
	if(timer == undefined) timer = 3500;
	if(title =='') title = "Alerta:";
	var template = $('<div class="alert alert-danger" role="alert"><button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button><i class="fa fa-exclamation-triangle fa-lg"></i> <strong>'+title+'</strong><br/> '+t+'</div>');
	$("#alertModal").prepend(template);
	template.hide().slideDown();

	if(timer!=null){
		setTimeout(function(){
			template.slideUp('slow');
		}, timer);
	}
	obj.focus().parent().addClass("has-error");
}
function checkLength(f, n, min, t){
	var o = $('#' + f);
	if (o.val().length < min) {
		o.focus();
		if(t == undefined)
			updateTips(o,n + " não pode ter menos que " +	min + " caracteres.");
		else
			updateTips(o,t);
		return false;
	} else {
		return true;
	}
}
function checkNumber(f, n, min, t){
	var o = $('#' + f);
	if (Number(o.val()) < min) {
		o.addClass("ui-state-error");
		o.focus();
		if(t == undefined)
			updateTips(o, n + " não pode ser menor que " +	min + ".");
		else
			updateTips(o,t);
		return false;
	} else {
		return true;
	}
}
function checkRegexp(f, regexp, t){
	var o = $('#' + f);
	if (!( regexp.test(o.val()))){
		o.addClass("ui-state-error");
		updateTips(t);
		return false;
	} else {
		return true;
	}
}

function checkCaracteresEspecial(obj,regex){
	var regExp = new RegExp(regex);
	var myString = obj.val();
	return myString.search(regExp);
}

function checkNumberString(obj){
	var alphaExp = /^[a-zA-Za-zÀ-ú-0-9\b\s]+$/;
    var string = obj.val().trim();
    if(string.match(alphaExp)) return true;
    else return false; 
}

////////////////////////////////////////////////////////////////////////////////
//Funcoes Especificas.
function _GET(name){
	var url   = window.location.search.replace("?", "");
	var itens = url.split("&");
	for(n in itens){
		if( itens[n].match(name) ) {
			return decodeURIComponent(itens[n].replace(name+"=", ""));
		}
	}
	return null;
}
function conveterValorFloat(valor){
	valor = remove(valor, ".");
	valor = valor.replace(",",".");
	valor = parseFloat(valor);
  return valor;
}

function moneyToFloat(v){
	v = remove(v,"R$").trim();
	v = conveterValorFloat(v);
	return v;
}


function converteFloatMoeda(valor){
    var inteiro = null, decimal = null, c = null, j = null;
    var aux = new Array();
    valor = ""+valor;
    c = valor.indexOf(".",0);
    //encontrou o ponto na string
    if(c > 0){
       //separa as partes em inteiro e decimal
       inteiro = valor.substring(0,c);
       decimal = valor.substring(c+1,valor.length);
    }else{
       inteiro = valor;
    }
     
    //pega a parte inteiro de 3 em 3 partes
    for (j = inteiro.length, c = 0; j > 0; j-=3, c++){
       aux[c]=inteiro.substring(j-3,j);
    }
     
    //percorre a string acrescentando os pontos
    inteiro = "";
    for(c = aux.length-1; c >= 0; c--){
       inteiro += aux[c]+'.';
    }
    //retirando o ultimo ponto e finalizando a parte inteiro
     
    inteiro = inteiro.substring(0,inteiro.length-1);
     
    decimal = parseInt(decimal);
    if(isNaN(decimal)){
       decimal = "00";
    }else{
       decimal = ""+decimal;
       if(decimal.length === 1){
          decimal = decimal+"0";
       }
    }
     
     
    valor = "R$ "+inteiro+","+decimal;
     
     
    return valor;

 }

///////////////////////////////////////////////////////////////////////////////
//Carregamento inicial do framework ///////////////////////////////////////////
$(function(){
	//Modal Excluir - Framework	
	function actionFormDel(){
		$('#formSearch').submit();
	}	
	
	$("#btDel").button({ icons:{primary:'ui-icon-trash'} }).click(function(){		
		var modal = createModal(actionFormDel, 'sm');
		modal.setTitle("Confirmação");
		modal.setMessage("Você quer realmente apagar esse registro?");
		modal.show();
	});
	
	$("#btn_add").click(function(){
		var link = window.location + '';
		link = link.split("&");
		window.location = link[0] +"&"+link[1]+"&formEdit=0";		
	});
	
	$('#btCheckAll').click(function(){
		var check = this.checked;			
		$('.btCheck').each(function(){
			this.checked = check;
		});			
	});

    $(".btLimpar").click(function(){
        $($(".btLimpar")[0].form).find("input,select,textarea").each(function(index){
            if(this.localName == "input" || this.localName == "textarea"){
                $(this).val("");
            }else if(this.localName == "select" ){
                $(this).val(0);
            }
            window.location.href = window.location.href;
        });
    });

	/*$("button[type='submit']").button({ icons:{primary:'ui-icon-check'} });
	$("#btAdd").button({ icons:{primary:'ui-icon-circle-plus'} }).click(function(){
		var link = window.location + '';
		link = link.split("&");
		window.location = link[0] + "&form=0";		
	});
	$("#btVoltar").button({ icons:{primary:'ui-icon-circle-arrow-w'} });
	$("#btDel").button({ icons:{primary:'ui-icon-trash'} }).click(function(){
		//$('#dialog_del').dialog('open');
		return false;
	});
	$("#btSearch").button({ icons:{primary:'ui-icon-search'} });
	$("#btInsertEdit").button({ icons:{primary:'ui-icon-disk'} });
	$('.btEdit div').hover(
		function(){ $(this).addClass('ui-state-hover'); }, 
		function(){ $(this).removeClass('ui-state-hover'); }
	);
	$('.buttonPag').hover(
		function(){ $(this).addClass('ui-state-hover'); }, 
		function(){ $(this).removeClass('ui-state-hover'); }
	);	
	$('#btCheckAll').click(function(){
		var check = this.checked;			
		$('.btCheck').each(function(){
			this.checked = check;
		});			
	});
	$('.tablelist tr').each(function(){
		$(this).hover(
			function(){ $(this).addClass('hover'); }, 
			function(){ $(this).removeClass('hover'); }
		);
	});
	$('.datepicker').each(function(index){
		$(this).datepicker();
	});
	$('#formInsertEdit').find('textarea').each(function(index){
		$(this).keydown(function(){
			if($(this).val().length > $(this).attr('maxlength')){
				$(this).val($(this).val().substring(0, $(this).attr('maxlength')));
			}		
		});
	});
	/*$('#dialog_del').dialog({
		autoOpen: false,
		width: 300,
		modal: true,
		buttons: {
			"Ok": function() { 
				$(this).dialog("close"); 
				$('#formSearch').submit();
			}, 
			"Cancelar": function() { 
				$(this).dialog("close"); 
			} 
		}
	});
	$("#btBack").button();
	$("#btNext").button();
	$(document).ajaxStart(function(){
		$('#loader').show();
	});	
	$(document).ajaxStop(function(){
		$('#loader').hide();
	});
	$(document).tooltip({track: true});*/
});
///////////////////////////////////////////////////////////////////////////////



(function($){
	 $.fn.upper = function(options){
		var config = {
		};
		var options = $.extend(config, options);
		$(this).keyup(function(){
		$(this).val($(this).val().toUpperCase());
		})
		$(this).css( "text-transform", "uppercase" );
	 }
})($)